package com.iteaj.iot.test.mqtt;

import cn.hutool.json.JSONUtil;
import com.iteaj.iot.Message;
import com.iteaj.iot.ProtocolType;
import com.iteaj.iot.client.protocol.ServerInitiativeProtocol;
import com.iteaj.iot.test.TestConst;
import com.iteaj.iot.test.TestProtocolType;
import com.iteaj.iot.test.TestStatusHeader;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * mqtt Broker服务主动请求客户端协议
 */
public class MqttBrokerPublishTestProtocol extends ServerInitiativeProtocol<MqttClientTestMessage> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public MqttBrokerPublishTestProtocol(MqttClientTestMessage requestMessage) {
        super(requestMessage);
    }

    @Override
    protected void doBuildRequestMessage(MqttClientTestMessage requestMessage) {
        Message.MessageHead head = requestMessage.getHead();
        TestProtocolType type = head.getType();
        if(type == TestProtocolType.WillTop) {
            logger.info(TestConst.LOGGER_PROTOCOL_DESC, "mqtt测试", "遗嘱测试"
                    , head.getEquipCode(), head.getMessageId(), "通过");
        }
    }

    @Override
    protected MqttClientTestMessage doBuildResponseMessage() {
        TestStatusHeader head = (TestStatusHeader) requestMessage().getHead();
        head.setResult(true);
        head.setType(TestProtocolType.CIReq);
        String headStr = JSONUtil.toJsonStr(head);
        head.setMessage(headStr.getBytes(StandardCharsets.UTF_8));

        return new MqttClientTestMessage(head, "broker");
    }

    @Override
    public ProtocolType protocolType() {
        return TestProtocolType.PIReq;
    }
}
